package com.weimob.xh.shiro;

import cn.hutool.json.JSONUtil;
import com.hazelcast.internal.util.JsonUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @projectName: xh-learn-record
 * @package: com.weimob.xh.shiro
 * @className: MyFilter
 * @author: chsun6
 * @description: TODO
 * @date: 2024/6/21 17:01
 * @version: 1.0
 */
public class MyFilter extends AccessControlFilter {
    // 未登录登陆返状态回码
    private int code;
    // 未登录登陆返提示信息
    private String message;

    public MyFilter(int code, String message) {
        this.code = code;
        this.message = message;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        Subject subject = SecurityUtils.getSubject();
        // 这里配合APP需求我只需要做登录检测即可
        if (subject != null && subject.isAuthenticated()) {
            // TODO 登录检测通过，这里可以添加一些自定义操作
            return Boolean.TRUE;
        }
        // 登录检测失败返货False后会进入下面的onAccessDenied()方法
        return Boolean.FALSE;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse servletResponse) throws Exception {
        PrintWriter out = null;
        try {
            // 这里就很简单了，向Response中写入Json响应数据，需要声明ContentType及编码格式
            servletResponse.setCharacterEncoding("UTF-8");
            servletResponse.setContentType("application/json; charset=utf-8");
            out = servletResponse.getWriter();
            out.write("失败了,code:" + code + ",message:" + message);
//            out.write(JSONUtil.toJsonStr(R.error(code, message)));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
        return Boolean.FALSE;
    }
}
